package cn.itcast.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.itcast.SetMealDao;
import cn.itcast.SetMealService;
import cn.itcast.pojo.CheckGroup;
import cn.itcast.pojo.CheckItem;
import cn.itcast.pojo.PageResult;
import cn.itcast.pojo.Setmeal;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;


    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeallist = setMealDao.findPage(queryString);
        return new PageResult(setmeallist.getTotal(), setmeallist.getResult());
    }

    @Override
    //新增套餐
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //绑定套餐和检查组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);


        }
    }

    @Override
    public List<Setmeal> fingAll() {
        List<Setmeal> setmealList = setMealDao.fingAll();
        return setmealList;
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setMealDao.findById(id);
        if (null != setmeal) {
            Integer setmealId = setmeal.getId();
            List<CheckGroup> checkGroupList = setMealDao.findGroupsBySetmealId(setmealId);
            if (CollectionUtil.isNotEmpty(checkGroupList)) {
                for (CheckGroup checkGroup : checkGroupList) {
                    List<CheckItem> checkItemlist = setMealDao.fingItemByCheckGroupId(checkGroup.getId());
                    checkGroup.setCheckItems(checkItemlist);
                }


            }
            setmeal.setCheckGroups(checkGroupList);

        }
        return setmeal;


    }

    //绑定套餐和检查组的多对多关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            setMealDao.setSetmealAndCheckGroup(map);
        }
    }
}
